import { database } from '../client'
import { mcpServers } from '../schema/models/mcpServers'
import { eq, and } from 'drizzle-orm'
import { getK8sClient } from '../services/k8s/k8sClient'
import * as k8s from '@kubernetes/client-node'
import yaml from 'js-yaml'
import Transaction from '../lib/Transaction'
import { Result } from '../lib/Result'

export async function fixMcpServerMisconfiguration() {
  const workspaceId = 1

  // Get all deployed MCP servers from workspace 1
  const servers = await database
    .select()
    .from(mcpServers)
    .where(and(eq(mcpServers.status, 'deployed')))

  console.log(
    `Found ${servers.length} deployed MCP servers in workspace ${workspaceId}`,
  )

  // Initialize Kubernetes client
  const kc = getK8sClient().kc
  const appsV1Api = kc.makeApiClient(k8s.AppsV1Api)
  const coreV1Api = kc.makeApiClient(k8s.CoreV1Api)
  const networkingV1Api = kc.makeApiClient(k8s.NetworkingV1Api)

  for (const server of servers) {
    console.log(`Processing MCP server: ${server.name} (${server.uniqueName})`)

    try {
      // Fetch the actual resources from Kubernetes
      const deployment = await appsV1Api.readNamespacedDeployment({
        name: server.uniqueName!,
        namespace: server.namespace!,
      })

      const service = await coreV1Api.readNamespacedService({
        name: server.uniqueName!,
        namespace: server.namespace!,
      })

      const ingress = await networkingV1Api.readNamespacedIngress({
        name: `${server.uniqueName}-ingress`,
        namespace: server.namespace!,
      })

      // Convert the resources to YAML manifest
      const resources = [deployment, service, ingress]

      // Clean up the resources by removing status and metadata fields that shouldn't be stored
      const cleanedResources = resources.map((resource) => ({
        ...resource,
        metadata: {
          ...resource.metadata,
          // Remove fields that are auto-generated by k8s
          resourceVersion: undefined,
          uid: undefined,
          generation: undefined,
          creationTimestamp: undefined,
          managedFields: undefined,
        },
        status: undefined, // Remove status field
      }))

      // Convert to YAML
      const manifestYaml = cleanedResources
        .map((resource) => yaml.dump(resource))
        .join('---\n')

      // Update the database with the actual manifest
      await new Transaction().call(async (tx) => {
        await tx
          .update(mcpServers)
          .set({
            k8sManifest: manifestYaml,
          })
          .where(eq(mcpServers.id, server.id))

        return Result.ok(undefined)
      })

      console.log(`✅ Updated manifest for ${server.name}`)
    } catch (error) {
      console.error(`❌ Failed to process ${server.name}:`, error)
      // Continue with the next server even if one fails
    }
  }

  console.log('✅ MCP server configuration fix completed')
}
